package image2

import (
	"errors"
	"github.com/nfnt/resize"
	"image"
	"image/color"
)

type Canvas struct {
	Path              string  // 图片路径
	Width             int     // 宽度
	Height            int     // 高度
	Color             string  // 底色 Color 与 Path 只会生效一个 以 Path 优先
	FontFile          string  // 字体文件
	Placeholder       [][]int // 占位符 判断像素点是否已被占用
	Canvas            *image.RGBA
	backgroundImage   image.Image
	backgroundColor   color.RGBA
	isBackgroundImage bool
}

func (b *Canvas) GenerateDrawCanvas() error {
	if len(b.Path) == 0 {
		if err := b.createColorBackground(); err != nil {
			return err
		}
	} else {
		b.isBackgroundImage = true
		if err := b.createImageBackground(); err != nil {
			return err
		}
	}

	// 生成占位数组
	b.Placeholder = make([][]int, b.Width)
	for i := range b.Placeholder {
		b.Placeholder[i] = make([]int, b.Height)
	}

	return nil
}

func (b *Canvas) createImageBackground() (err error) {
	b.backgroundImage, err = loadImage(b.Path)
	if err != nil {
		return errors.New("load image2 " + b.Path + " failed. " + err.Error())
	}
	if b.Width > 0 || b.Height > 0 {
		b.backgroundImage = resize.Resize(uint(b.Width), uint(b.Height), b.backgroundImage, resize.Lanczos3)
	} else {
		b.Height, b.Width = loadImageSize(b.backgroundImage)
	}
	b.Canvas = image.NewRGBA(image.Rect(0, 0, b.Width, b.Height))

	return nil
}

func (b *Canvas) createColorBackground() error {
	b.Canvas = image.NewRGBA(image.Rect(0, 0, b.Width, b.Height))
	return nil
}

// 填充未画满的像素点
func (b *Canvas) FullEmptyPixel() error {
	if b.isBackgroundImage == false {
		b.backgroundColor = rgbaColor(b.Color, 255)
		for y := 0; y < b.Height; y++ {
			for x := 0; x < b.Width; x++ {
				if b.Placeholder[x][y] == 0 {
					b.Canvas.Set(x, y, b.backgroundColor)
				}
			}
		}
	} else {
		for y := 0; y < b.Height; y++ {
			for x := 0; x < b.Width; x++ {
				if b.Placeholder[x][y] == 0 {
					b.Canvas.Set(x, y, b.backgroundImage.At(x, y))
				}
			}
		}
	}

	return nil
}
